<?php
	/*
		CMA Version: 1.0
		
		
		Developed by: Ammar
	*/
	
	
	function usernameExists($username,$password)
	{
		
		global $db,$db_table_prefix;
		
		$sql = "SELECT *
				FROM ".$db_table_prefix."Users
				WHERE
				Username = '".$db->sql_escape($username)."' and PASSWORD='".$db->sql_escape($password)."'
				LIMIT 1";
		//die($sql);
		if(returns_result($sql) > 0)
			return true;
		else
			return false;
	}
	
	function emailExists($email)
	{
		global $db,$db_table_prefix;
	
		$sql = "SELECT * FROM ".$db_table_prefix."Users
				WHERE
				Email = '".$db->sql_escape(sanitize($email))."'
				LIMIT 1";
	
		if(returns_result($sql) > 0)
			return true;
		else
			return false;	
	}
	
	//Function lostpass var if set will check for an active account.
	function validateActivationToken($token,$lostpass=NULL)
	{
		global $db,$db_table_prefix;
		
		if($lostpass == NULL) 
		{	
			$sql = "SELECT *
					FROM ".$db_table_prefix."Users
					WHERE 
					Activation ='".$db->sql_escape(trim($token))."'
					LIMIT 1";
		}
		else 
		{
			 $sql = "SELECT *
			 		FROM ".$db_table_prefix."Users
					WHERE 
					Activation ='".$db->sql_escape(trim($token))."'
					AND
					LostPasswordRequest = 1 LIMIT 1";
		}
		//die($sql);
		
		if(returns_result($sql) > 0)
			return true;
		else
			return false;
	}
	
	
	/*
		we have four type of activation
		0 : not Active
		1 : not Complete , to complete it fill user Details ("inProcess")
		2 : waiting approve from admin("pending").
		3 : approved from admin.
		4 : 5 not approved.
	*/
	function setUserActive($token='',$value,$user_id='')
	{
	
		global $db,$db_table_prefix;
		if($token!=''){
			$sql = "UPDATE ".$db_table_prefix."Users
					SET Active = ".$value."
					WHERE
					Activation ='".$db->sql_escape(trim($token))."'
					LIMIT 1";
			}else{
				$sql = "UPDATE ".$db_table_prefix."Users
					SET Active = ".$value."
					WHERE
					uid ='".$db->sql_escape(trim($user_id))."'
					LIMIT 1";
			}
			
		return ($db->sql_query($sql));
	}
	
	
	//You can use a activation token to also get user details here
	function fetchUserDetails($username=NULL,$token=NULL)
	{
		global $db,$db_table_prefix; 
		
		if($username!=NULL) 
		{  
			$sql = "SELECT * FROM ".$db_table_prefix."Users
					WHERE
					Username = '".$db->sql_escape(sanitize($username))."'
					LIMIT
					1";
		}
		else
		{
			$sql = "SELECT * FROM ".$db_table_prefix."Users
					WHERE 
					Activation = '".$db->sql_escape(sanitize($token))."'
					LIMIT 1";
		}
		
		 
		$result = $db->sql_query($sql);
		
		$row = $db->sql_fetchrow($result);
		
		return ($row);
	}
	
	function flagLostPasswordRequest($username,$value)
	{
		global $db,$db_table_prefix;
		
		$sql = "UPDATE ".$db_table_prefix."Users
				SET LostPasswordRequest = '".$value."'
				WHERE
				Username_Clean ='".$db->sql_escape(sanitize($username))."'
				LIMIT 1
				";
		
		return ($db->sql_query($sql));
	}
	
	function updatePasswordFromToken($pass,$token)
	{
		global $db,$db_table_prefix;
		
		$new_activation_token = generateActivationToken();
		
		$sql = "UPDATE ".$db_table_prefix."Users
				SET Password = '".$db->sql_escape($pass)."',
				Activation = '".$new_activation_token."'
				WHERE
				Activation = '".$db->sql_escape(sanitize($token))."'";
		
		return ($db->sql_query($sql));
	}
	
	function emailUsernameLinked($email,$username)
	{
		global $db,$db_table_prefix;
		
		$sql = "SELECT Username,
				Email FROM ".$db_table_prefix."Users
				WHERE Username_Clean = '".$db->sql_escape(sanitize($username))."'
				AND
				Email = '".$db->sql_escape(sanitize($email))."'
				LIMIT 1
				";
		
		if(returns_result($sql) > 0)
			return true;
		else
			return false;
	}
	
	
	function isUserLoggedIn()
	{
		global $loggedInUser,$db,$db_table_prefix;
		
		$sql = "SELECT User_ID,
				Password
				FROM ".$db_table_prefix."Users
				WHERE
				User_ID = '".$db->sql_escape($loggedInUser->user_id)."'
				AND 
				Password = '".$db->sql_escape($loggedInUser->hash_pw)."' 
				AND
				Active = 1
				LIMIT 1";
		
		if($loggedInUser == NULL)
		{
			return false;
		}
		else
		{
			//Query the database to ensure they haven't been removed or possibly banned?
			if(returns_result($sql) > 0)
			{
					return true;
			}
			else
			{
				//No result returned kill the user session, user banned or deleted
				$loggedInUser->userLogOut();
			
				return false;
			}
		}
	}
	
	//This function should be used like num_rows, since the PHPBB Dbal doesn't support num rows we create a workaround
	function returns_result($sql)
	{
		global $db;
		
		$count = 0;
		$result = $db->sql_query($sql);
		
		while ($row = $db->sql_fetchrow($result))
		{
		  $count++;
		}
		
		$db->sql_freeresult($result);
		
		return ($count);
	}
	
	//Generate an activation key 
	function generateActivationToken()
	{
		$gen;
	
		do
		{
			$gen = md5(uniqid(mt_rand(), false));
		}
		while(validateActivationToken($gen));
	
		return $gen;
	}
	
	function updateLastActivationRequest($new_activation_token,$username,$email)
	{
		global $db,$db_table_prefix; 
		
		$sql = "UPDATE ".$db_table_prefix."Users
		 		SET Activation = '".$new_activation_token."',
				LastActivationRequest = '".time()."'
				WHERE Email = '".$db->sql_escape(sanitize($email))."'
				AND
				Username_Clean = '".$db->sql_escape(sanitize($username))."'";
		
		return ($db->sql_query($sql));
	}
	
	function getUserSessionObject($username)
	{
		global $loggedInUser,$db,$db_table_prefix;
		$userobj= new stdclass;
		$result=fetchUserDetails($username);
		//print_r ($result);
		
		  $userobj->username=$result[Username];
		  $userobj->uid=$result[Uid];
		  $userobj->password=$result[PASSWORD];
		  $userobj->email=$result[Email];
		  $userobj->rid=$result[Rid];
		  $userobj->cid=$result[CID];
		  $userobj->active=$result[Active];
		  $userobj->activation=$result[Activation];
						
		return ($userobj);
	}
	
	function sanitize($a)
	{
		return $a;
		//return strtolower(strip_tags(trim(($str))));
	}
	
	
	function AddUser($username,$email,$Activation,$Rid,$Cid){
	global $db,$emailActivation,$websiteUrl,$db_table_prefix;
	//generate random password
	$vowels = 'aeuy';
	$consonants = 'bdghjmnpqrstvz';	
	$consonants .= 'BDGHJLMNPQRSTVWXZ';
	$consonants .= '23456789';
 
	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++) {
		if ($alt == 1) {
			$password .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$password .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	
	
	//Insert the user into the database providing no errors have been found.
	$sql = "INSERT INTO ".$db_table_prefix."Users (
			Username,
			Password,
			Email,
			Activation,
			SignUpDate,
			Rid,
			Cid
			)
			VALUES (
			'".$db->sql_escape($username)."',
			'".$password."',
			'".$email."',
			'".$Activation."',
			'".time()."',
			$Rid,
			$Cid
			)";
			//die($sql);
	$db->sql_query($sql);

}

	function ChangePassword($pass,$token,$active=1)
	{
		global $db,$db_table_prefix;
		
		$new_activation_token = generateActivationToken();
		
		$sql = "UPDATE ".$db_table_prefix."Users
				SET Password = '".$db->sql_escape($pass)."',
				Activation ='".$db->sql_escape(sanitize($new_activation_token))."',
				Active=".$active."
				WHERE
				Activation = '".$db->sql_escape(sanitize($token))."'";
		//die($sql);
		return ($db->sql_query($sql));
	}
	
function AddUserDetails($arName,$enName,$PhoneNo,$MobileNo,$IdentityNumber,$Fid)
	{
	global $db,$db_table_prefix;
	//print_r($_SESSION[User]);
	
	$sql= "INSERT INTO details set 
	details.Uid=".$_SESSION[User]->uid.",
	details.EnName='$enName',
	details.ARName='$arName',
	details.PhoneNo='$PhoneNo',
	details.MobileNo='$MobileNo',
	details.IdentityNumber='$IdentityNumber',
	details.Fid=$Fid"
	;
	//echo($sql);
	
	return ($db->sql_query($sql));
	}
	
	function FileUpload()
	{
	global $my_upload, $db,$db_table_prefix;
	$my_upload->the_temp_file = $_FILES['IdentityCopy']['tmp_name'];
	$my_upload->the_file = $_FILES['IdentityCopy']['name'];
	$my_upload->http_error = $_FILES['IdentityCopy']['error'];
	$full_path = $my_upload->upload_dir.$my_upload->file_copy;
	$maxfileid =getlastinsertfileid();
		if (!$maxfileid[comid])
			$maxfileid=1;
			$my_upload->upload($maxfileid[comid]); // new name is an additional filename information, use this to rename the uploaded file
			$full_path = $my_upload->upload_dir.$my_upload->file_copy;
			$ftype=end(explode('.', $full_path));
			$sql="insert into files set fpath='".$maxfileid[comid]."', Ftype='$ftype'";
			$db->sql_query($sql);
//$file1=$my_upload->file_copy;
		return ($maxfileid[comid]);}

	function getlastinsertfileid()
	{
	global $db,$db_table_prefix;
	$sql = "SELECT MAX(fid) comid FROM files";
	
     $result=$db->sql_fetchrowset($db->sql_query($sql));

		return ($result[0]);
  }	
	function userdashboard($user_object){
		/*  Admin User */
		if($user_object->rid==1){
			$url="tpls/main.tpl";
		}
		/*  CEO User */
		if($user_object->rid==2){
		//die('here');
				if($user_object->active==0){
					$_SESSION['User']=null;
					header ("Location: index.php");
					exit;
				}
				if($user_object->active==1){
					header ("Location: activateceo.php?action=ceodetails");
					exit;
				}
				if($user_object->active==2){
					$url="tpls/ceo-main.tpl";
					//die('here');
				}
				/* toDo:pending user*/
				/*
				if($user_object->active==3){
					header ("Location: index.php");
				}
				*/
				
				
		}
		if($user_object->rid==3){
			$url="tpls/co-main.tpl";
		}
		//die($url);
		return $url;
	}	
?>